﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using System.Threading;

using FCNS.Utility;
using FCNS.Controls.Calendars;

using FCNS.KeepMoney.UI;
using FCNS.KeepMoney.Configuration;
using FCNS.KeepMoneyLibrary.Data;
using FCNS.KeepMoneyLibrary.Util;
using FCNS.KeepMoney.Util;
using FCNS.KeepMoney.Plugins;

using BrightIdeasSoftware;

namespace FCNS.KeepMoney.Forms
{
    public partial class MainForm : ParentForm
    {
        public MainForm()
        {
            InitializeComponent();

            this.Icon = Properties.Resources.rmb;
            notifyIcon1.Icon = this.Icon;
            notifyIcon1.Text = AppDefines.kmoneyInstructions;

            InitControlsWhenApplicationStart();

            ThreadPool.QueueUserWorkItem(ConfigOtherParamWhenApplicationStart, toolMenuAdsense);

            adsenseTimer.Interval = 10000;
            adsenseTimer.Tick += new EventHandler(adsenseTimer_Tick);
            adsenseTimer.Start();

            WinUtil.RegisterHotKey(this.Handle, AppDefines.hotkeyNewEntry, (Keys)configApp.HotkeyEntry);
            WinUtil.RegisterHotKey(this.Handle, AppDefines.hotkeyShowMainForm, (Keys)configApp.HotkeyForm);

            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize(this);
            pluginManager.Initialize(pluginDefaultHost);
            pluginManager.UnloadAllPlugins();
            pluginManager.LoadAllPlugins(UrlUtil.GetFileDirectory(AppDefines.appPath, false, true));

            splitContainerLeft.SplitterDistance = configMainForm.LeftPanelWidth;
            splitContainerLeft.SplitterMoved += new SplitterEventHandler(splitContainerLeft_SplitterMoved);
            splitContainerCenter.SplitterDistance = configMainForm.ChartHeight;
            splitContainerCenter.SplitterMoved += new SplitterEventHandler(splitContainerChart_SplitterMoved);

            ApplyTranslate();


            if (configApp.FileOpenRecords.Count != 0)
                if (Program.OpenSoftByKMDfile||configApp.AutoOpenKMD)
                    if (IsSuccessfullyOpenTheKMDfile(configApp.FileOpenRecords[0].FilePath))
                        return;

            UpdateUI(UIState.Init);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            OnFormSizeChanged(null, null);//饼型图表尺寸的更新

            //以下内容放这里是防止翻译软件 Translate 的错误
            for (int m = 1; m < DateTime.Now.Month; m++)
                menuDataBilling.DropDownItems.Add(DateTime.Now.AddMonths(-m).ToString(AppDefines.dateFormat_yyyy_MM));

            if (configApp.FileOpenRecords.Count != 0)
                return;

            if (MessageBox.Show(LanguageUtil.首次使用KeepMoney是否新建数据库,
                "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                OnNewKMD(null, EventArgs.Empty);
        }

        private void SetMenu(ToolStripMenuItem item)
        {
            toolMenuAdsense.DropDownItems.Add(item);
        }
        public delegate void SetToolMenu(ToolStripMenuItem item);

        private void ConfigOtherParamWhenApplicationStart(object adsense)
        {
            System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
            try { xml.Load(AppDefines.AdsenseUrl); }
            catch { return; }

            //广告
            Donations.Donations.Init(xml);

            //推广
            ToolStripSplitButton tssb = (ToolStripSplitButton)adsense;
            foreach (System.Xml.XmlNode node in xml.SelectNodes("Ads/Url"))
            {
                if (!node.SelectSingleNode("Tag").InnerText.Contains("4"))
                    continue;

                ToolStripMenuItem item = new ToolStripMenuItem(node.SelectSingleNode("Name").InnerText);
                item.Tag = node.SelectSingleNode("Link").InnerText;
                this.Invoke(new SetToolMenu(SetMenu), item);
            }
            //汇率
            ExchangeField.Init();
            ////加载 Python 脚本
            //if (!Directory.Exists(AppDefines.pythonPath))
            //    Directory.CreateDirectory(AppDefines.pythonPath);

            //foreach (string file in Directory.GetFiles(AppDefines.pythonPath))
            //{
            //    PythonUtil p = new PythonUtil();
            //    p.LoadPython(file);
            //}
        }

        private void MainForm_Move(object sender, EventArgs e)
        {
            if (this.WindowState != FormWindowState.Normal)
                return;

            configMainForm.X = this.Left;
            configMainForm.Y = this.Top;
        }

        private void OnFormSizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                return;

            if (this.WindowState == FormWindowState.Maximized)
                configMainForm.Maximized = true;
            else
            {
                configMainForm.Maximized = false;
                configMainForm.Width = this.Width;
                configMainForm.Height = this.Height;

            }

            toolMenuNormal.Margin = new Padding(panelLeft.Width - 60, 0, 0, 0);
            chartPanel1.Width = chartPanel1.Parent.Width / 2;
            chartPanel2.Width = chartPanel1.Width;
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && configMainForm.CloseToTray)
            {
                e.Cancel = true;
                ChangeMainFormStatus();
            }
            else
            {
                OnCloseKMD(null, null);
            
                WinUtil.UnregisterHotKey(this.Handle, AppDefines.hotkeyNewEntry);
                WinUtil.UnregisterHotKey(this.Handle, AppDefines.hotkeyShowMainForm);

                //WriteFileOpenRecord(null);
                SaveConfig();
            }
        }

        #region  文件
        private void OnNewKMD(object sender, EventArgs e)
        {
            string kmdFilePath = GetNewKMDfilePath(KMDformat.KMD);
            if (kmdFilePath == string.Empty)
                return;

            OnCloseKMD(sender, e);
            kmData = new KMData(kmdFilePath, true);
            ConfigControlsWhenOpenKMDfile(kmdFilePath);
            WriteFileOpenRecord(kmdFilePath);
            kmData.WriteXml(kmdFilePath, XmlWriteMode.WriteSchema);

        }

        private void OnOpenKMD(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = AppDefines.kmdFilter;
                if (ofd.ShowDialog() != DialogResult.OK)
                    return;

                OnCloseKMD(sender, e);

                IsSuccessfullyOpenTheKMDfile(ofd.FileName);
            }
        }

        private void OnOpenUrlKMD(object sender, EventArgs e)
        {
            AppDefines.HelpTopic.Show(AppDefines.HelpTopic.KMinWeb);
        }

        void FileOpenRecord_Click(object sender, EventArgs e)
        {
            string file = ((ToolStripMenuItem)sender).Text;

            OnCloseKMD(sender, e);

            IsSuccessfullyOpenTheKMDfile(file);
        }

        private void OnSaveKMD(object sender, EventArgs e)
        {
            if (!toolMenuSave.Enabled)
                return;

            string file = configApp.FileOpenRecords[0].FilePath;
            if (!File.Exists(file))
            {
                file = string.Empty;
                if (MessageBox.Show(file + LanguageUtil.文件无法访问_可能文件已移除_是否继续保存,
                      "⊙﹏⊙", MessageBoxButtons.YesNo) != DialogResult.Yes)
                { return; }

                file = GetNewKMDfilePath(KMDformat.KMD);
            }

            OnSaveAsKMD(file, EventArgs.Empty);

            toolMenuSave.Enabled = false;
        }

        private void OnSaveAsKMD(object sender, EventArgs e)
        {
            string path;
            if (sender is string)
                path = sender.ToString();
            else
                path = GetNewKMDfilePath(KMDformat.KMD);

            if (string.IsNullOrEmpty(path))
                return;

            if (!configApp.EncryptionData)
            {
                kmData.WriteXml(path, XmlWriteMode.WriteSchema);
                //FileInfo fi = new FileInfo(path);
                //if (fi.Length / 1024 / 8 > 5)
                //    MessageBox.Show("数据库文件过大,是否开启压缩功能?");
            }
            else
            {
                FileStream fs = new FileStream(path, FileMode.Create,
                  FileAccess.Write, FileShare.None);

                GZipStream gz = new GZipStream(fs, CompressionMode.Compress);
                StreamWriter writer = new StreamWriter(gz);
                kmData.WriteXml(writer, XmlWriteMode.WriteSchema);
                writer.Flush();
                writer.Close();

                fs.Dispose();
                gz.Dispose();
            }
        }

        private void OnPrint(object sender, EventArgs e)
        {
            ListView lists = null;
            //if (tabControlExMain.SelectedItem == tabDetail)
            //    lists = listViewExDetail;
            if (configMainForm.UItype == UiType.Money)
                lists = listViewEntry;

            if (lists == null)
                MessageBox.Show(LanguageUtil.当前内容不支持打印);
            else
                PrintEntryList(lists);
        }

        private void OnCloseKMD(object sender, EventArgs e)
        {
            if (!toolMenuMode.Enabled)
                return;

            if (toolMenuSave.Enabled)
            {
                switch (MessageBox.Show(LanguageUtil.是否保存数据库, "", MessageBoxButtons.YesNoCancel))
                {
                    case DialogResult.Yes:
                        OnSaveKMD(sender, e);
                        break;
                    case DialogResult.Cancel:
                        return;
                }
            }

            WriteFileOpenRecord(null);

            kmData.Close();

            UpdateUI(UIState.Init);
        }

        private void OnChangePwd(object sender, EventArgs e)
        {
            bool hasAuthorized;
            DisplayTheLoginForm(LoginFormState.ChangePwd, out hasAuthorized);
        }

        private void OnLockKMD(object sender, EventArgs e)
        {
            bool hasAuthorized;
            DisplayTheLoginForm(LoginFormState.Lock, out hasAuthorized);
        }

        private void OnAppExit(object sender, EventArgs e)
        {
            OnSaveKMD(sender, e);
            this.Close();
        }
        #endregion

        #region 编辑
        private void OnMenuEditOpening(object sender, EventArgs e)
        {
            if (menuEdit.DropDownItems.Count != (TheGroupMenu.Count + TheEntryMenu.Count + TheAdditionMenu.Count + 1))
            {
                menuEdit.DropDownItems.Clear();
                menuEdit.DropDownItems.AddRange(TheGroupMenu);
                menuEdit.DropDownItems.Add(new ToolStripSeparator());
                menuEdit.DropDownItems.AddRange(TheEntryMenu);
                menuEdit.DropDownItems.AddRange(TheAdditionMenu);

                menuEdit.ShowDropDown();
            }
            UpdateUI(UIState.ConfigEditMenu);
        }
        #endregion

        #region 数据
        private void OnPurseConfig(object sender, EventArgs e)
        {
            PurseForm p = new PurseForm();
            p.ShowDialog();
        }

        private void OnRegularConfig(object sender, EventArgs e)
        {
            RegularEntrysForm r = new RegularEntrysForm();
            r.Init();
            r.ShowDialog();
        }

        private void OnBuildBill(object sender, ToolStripItemClickedEventArgs e)
        {
            BillUtil.GenerateBilling(DateTime.ParseExact(e.ClickedItem.Text, AppDefines.dateFormat_yyyy_MM, null));
        }

        private void OnImportData(object sender, EventArgs e)
        {
            ImportForm f = new ImportForm();
            if (f.Init(null))
                f.ShowDialog();
        }

        private void OnExportData(object sender, EventArgs e)
        {
            int tag = -1;
            ImportForm f = new ImportForm();

            if (((ToolStripMenuItem)sender).Tag != null)
                tag = (int)((ToolStripMenuItem)sender).Tag;

            switch (tag)
            {
                case 0://群组
                    f.Init(entryField.FindAll(ef =>
                    {
                        return ef.GroupId == (
                            (GroupField)treeViewExGroup.SelectedNode.Tag).Id;
                    }));
                    break;

                default://主菜单,工具栏,账务记录(tag=1)
                    f.Init((List<EntryField>)listViewEntry.Objects);
                    break;
            }

            f.ShowDialog();
        }

        private void OnScanData(object sender, EventArgs e)
        {
            if (MessageBox.Show("企业版功能,是否访问订购页面?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                AppDefines.HelpTopic.Show(AppDefines.HelpTopic.KMinWeb);

            return;
            ScanForm f = new ScanForm();
            f.ShowDialog();
        }

        private void OnInterestConfig(object sender, EventArgs e)
        {
            InterestForm f = new InterestForm();
            f.Init();
            f.ShowDialog();
        }

        private void OnFieldConfig(object sender, EventArgs e)
        {

        }

        #endregion

        #region 工具
        private void OnStyleDesign(object sender, EventArgs e)
        {
            PrintForm p = new PrintForm();
            p.Init(listViewEntry, LanguageUtil.收支明细, AppDefines.kmoneyInstructions, "", 1);
            p.Show(this);
        }

        private void OnPluginManage(object sender, EventArgs e)
        {
            PluginsForm p = new PluginsForm();
            p.InitEx(pluginManager);
            p.Show(this);
        }

        private void OnOptionClick(object sender, EventArgs e)
        {
            OptionForm of = new OptionForm();
            of.ShowDialog();
        }

        private void OnShowCalcForm(object sender, EventArgs e)
        {
            CalcForm cf = new CalcForm();
            cf.Show(this);
        }

        private void menuToolMaintain_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("数据没有异常");
            //return;

            if (MessageBox.Show(LanguageUtil.此操作耗时_是否继续, "", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            //群组
            foreach (GroupField group in groupField)
                if (groupField.Find(gf => { return gf.Id == group.ParentGroupId; }) == null)
                    group.ParentGroupId = 0;

            //MaintainForm f = new MaintainForm();
            //f.ShowDialog();
        }

        private void menuToolTeach_Click(object sender, EventArgs e)
        {
            MsgForm f = new MsgForm();
            f.Show();
        }
        #endregion

        #region 视图
        private void OnLanguageChanged(object sender, EventArgs e)
        {
            LanguageForm f = new LanguageForm();
            f.Init();
            if (f.ShowDialog() == DialogResult.OK)
                ApplyTranslate();
        }

        private void OnHotItemStyleChanged(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == menuViewDisplayMiniForm)
                configMainForm.BusinessCardOverlay = !menuViewDisplayMiniForm.Checked;
            else
            {
                for (int i = 2; i < 7; i++)
                    ((ToolStripMenuItem)menuViewHotItemStyle.DropDownItems[i]).Checked = false;

                ((ToolStripMenuItem)e.ClickedItem).Checked = true;
            }

            switch (e.ClickedItem.Name)
            {
                case "hotItemStyleNone":
                    configMainForm.HotItemStyle = HotItemStyleEnum.None;
                    break;
                case "hotItemStyleTextColor":
                    configMainForm.HotItemStyle = HotItemStyleEnum.TextColor;
                    break;
                case "hotItemStyleBorder":
                  configMainForm.HotItemStyle = HotItemStyleEnum.Border;
                    break;
                case "hotItemStyleLightbox":
                   configMainForm.HotItemStyle = HotItemStyleEnum.Lightbox;
                    break;
                case "hotItemStyleTranslucent":
                   configMainForm.HotItemStyle = HotItemStyleEnum.Translucent;
                    break;
            }
            HotItemStyleUtil.SetHotItemStyle(listViewEntry, configMainForm.BusinessCardOverlay);
        }

        private void OnBankItemClick(object sender, ToolStripItemClickedEventArgs e)
        {
            BankField bank = (BankField)e.ClickedItem.Tag;
            bank.Visible = !bank.Visible;
            ShowEntryData();
            Program.SaveKMD = true;
        }

        private void OnMenuColumnItemClick(object sender, ToolStripItemClickedEventArgs e)
        {
            ConfigListViewEntrysAndMenuItemColumn((ToolStripMenuItem)e.ClickedItem);
        }

        private void OnShowSubGroupEntry(object sender, EventArgs e)
        {
            configMainForm.ShowSubGroupEntry = !configMainForm.ShowSubGroupEntry;
            ShowEntryData();
        }

        private void OnShowOverdueData(object sender, EventArgs e)
        {
            configApp.ShowOverdueData = !configApp.ShowOverdueData;
            ShowEntryData();
            gtdView.UpdateGtdView(true);
        }

        //private void OnShowBusinessCardOverlay(object sender, EventArgs e)
        //{
        //    configMainForm.BusinessCardOverlay = menuViewDisplayMiniForm.Checked;
        //}

        private void OnShowGroups(object sender, EventArgs e)
        {
            configMainForm.DisplayGroups = menuViewDisplayGroups.Checked;
            ListViewDisplayGroups();
            listViewEntry.BuildList();
        }
        #endregion

        #region 帮助
        private void OnMobile(object sender, EventArgs e)
        {
            AppDefines.WebSite.Show(AppDefines.WebSite.downloadUrl);
        }

        private void OnAboutMe(object sender, EventArgs e)
        {
            AboutForm a = new AboutForm();
            a.ShowDialog();
        }

        private void OnUpdate(object sender, EventArgs e)
        {
            AppDefines.WebSite.Show(string.Empty);
        }

        private void OnDonate(object sender, EventArgs e)
        {
            AppDefines.WebSite.Show(AppDefines.WebSite.DonationsUrl);
        }

        private void OnOpenWebSite(object sender, EventArgs e)
        {
            AppDefines.WebSite.Show(string.Empty);
        }

        private void OnSendMail(object sender, EventArgs e)
        {
            TextForm f = new TextForm();
            f.Init("信息反馈", "谢谢你的支持", string.Empty);
            f.UsedByMutliTextEdit();
            if (f.ShowDialog() != DialogResult.OK)
                return;

            Mail m = new Mail();
            m.SendMail(f.GetText);
        }
        #endregion

        #region 工具栏
        private void OnNewEntryButtonClick(object sender, EventArgs e)
        {
            EntryForm ef = new EntryForm();
            ef.Init((GroupField)treeViewExGroup.SelectedNode.Tag);
            if (ef.ShowDialog() != DialogResult.OK)
                return;

            UpdateUI(UIState.DataHasBeenChanged);
        }

        private void OnChangedMode(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case System.Windows.Forms.MouseButtons.Left:
                    if (configMainForm.UItype == UiType.Money)
                    {
                        InitGtd();
                        configMainForm.UItype = UiType.Gtd;
                    }
                    else
                    {
                        configMainForm.UItype = UiType.Money;
                        InitMoney();
                    }

                    break;

                case System.Windows.Forms.MouseButtons.Middle:
                    if (configMainForm.UItype == UiType.Money)
                        return;

                    configMainForm.UItype = UiType.Money;
                    InitMoney();
                    break;

                case System.Windows.Forms.MouseButtons.Right:
                    if (configMainForm.UItype == UiType.Book)
                        return;

                    MessageBox.Show("账簿模式 暂未开放");
                    break;
            }
            ReLoadEntry();
        }

        private void OnShowMainMenu(object sender, EventArgs e)
        {
            contextMenuStripMain.Show(MousePosition);
        }

        private void toolMenuAlert_Click(object sender, EventArgs e)
        {
            MsgForm f = new MsgForm();
            foreach (EntryField ef in (List<EntryField>)toolMenuAlert.Tag)
                f.Add(ef);

            f.ShowDialog();
        }

        private void OnChartNormalClick(object sender, EventArgs e)
        {
            UpdateChart(ChartType.Normal);
        }
        #region 图表 常规
        private void linkLabelBalance_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<XY> xy = new List<XY>();
            foreach (BankField f in bankField.FindAll(bf => { return bf.Balance > 0; }))
                xy.Add(new XY(f.Name, f.Balance));

            ChartUtil.ShowChart(ChartType.Normal, chartPanel1, xy);
        }

        private void linkLabelCredit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<XY> xy = new List<XY>();
            foreach (BankField f in bankField.FindAll(bf => { return bf.Credit > 0; }))
                xy.Add(new XY(f.Name,f.AvailableCredit()));

            ChartUtil.ShowChart(ChartType.Normal, chartPanel1, xy);
        }

        private void linkLabelLoan_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<EntryField> fields = (List<EntryField>)linkLabelLoan.Tag;
            listViewEntry.SetObjects(fields);

            List<XY> xy = new List<XY>();
            foreach (EntryField ef in fields)
                xy.Add(new XY(ef.columnGroupName, ef.Money));

            ChartUtil.ShowChart(ChartType.Normal, chartPanel1, xy);
        }

        private void linkLabelRepayment_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<EntryField> fields = (List<EntryField>)linkLabelRepayment.Tag;
            listViewEntry.SetObjects(fields);

            List<XY> xy = new List<XY>();
            foreach (EntryField ef in fields)
                xy.Add(new XY(ef.columnGroupName, ef.Money));

            ChartUtil.ShowChart(ChartType.Normal, chartPanel1, xy);
        }
        #endregion

        private void OnChartLineClick(object sender, EventArgs e)
        {
            UpdateChart(ChartType.Line);
        }

        private void OnChartHistogramClick(object sender, EventArgs e)
        {
            UpdateChart(ChartType.Histogram);
        }

        private void OnChartPieClick(object sender, EventArgs e)
        {
            UpdateChart(ChartType.Pie);
        }

        private void OnListViewEntryFilter(object sender, EventArgs e)
        {
            TextMatchFilter filter = null;
            if (!String.IsNullOrEmpty(toolMenuFilter.Text))
            {
                filter = TextMatchFilter.Contains(listViewEntry, toolMenuFilter.Text);

            }
            if (filter == null)
                listViewEntry.DefaultRenderer = null;
            else
                listViewEntry.DefaultRenderer = new HighlightTextRenderer(filter);

            HighlightTextRenderer highlightingRenderer = listViewEntry.GetColumn(0).Renderer as HighlightTextRenderer;
            if (highlightingRenderer != null)
                highlightingRenderer.Filter = filter;

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            listViewEntry.ModelFilter = filter;
            stopWatch.Stop();
        }


        private void OnAdsenseClick(object sender, ToolStripItemClickedEventArgs e)
        {
            Debug.Assert(e.ClickedItem.Tag != null, "FCNS.KeepMoney.Forms.MainForm.OnAdsenseClick(object sender, ToolStripItemClickedEventArgs e)");

            System.Diagnostics.Process.Start(e.ClickedItem.Tag.ToString());
        }
        private void OnAdsenseClick2(object sender, MouseEventArgs e)
        {
            if (toolMenuAdsense.Tag == null)
                return;

            if (e.X < toolMenuAdsense.Width - 15)
                System.Diagnostics.Process.Start(toolMenuAdsense.Tag.ToString());
        }
        private void OnAdsenseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }
        private void OnAdsenseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        }
        #endregion

        #region  侧边栏
        private void OnNewEntry(object sender, EventArgs e)
        {
            EntryField field = new EntryField(((GroupField)treeViewExGroup.SelectedNode.Tag).Id,bankField[comboBoxPurse.SelectedIndex].Id,
                dateTimePickerEntry.Value, numericUpDownEntryMoney.Value, KMDEntryType.Normal);

            if (field.Row == null)
            {
                MessageBox.Show(LanguageUtil.钱袋余额不足或金额为零);
                return;
            }
            else
            {
                field.AddRowToDataTable();
                field.columnName = textBoxEntryName.Text.Trim();
            }

            UpdateUI(UIState.DataHasBeenChanged);

            textBoxEntryName.Clear();
            numericUpDownEntryMoney.Value = 0;
        }

        private void OnEntrysFilterModeChanged(object sender, EventArgs e)
        {
            DateTime dtS = Program.YearShown, dtE = Program.YearShown;
            switch (comboBoxSearch.SelectedIndex)
            {
                case 0:
                    dtE = Program.YearShown;
                    dtS = Program.YearShown.AddMonths(-1).AddDays(1);
                    break;
                case 1:
                    dtS = DateTime.ParseExact(DateTime.Now.ToString("yyyyMM")
                        + "01", "yyyyMMdd", null);
                    dtE = dtS.AddDays(DateTime.DaysInMonth(dtS.Year, dtS.Month) - 1);
                    break;
                case 2:
                    dtS = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek);
                    if (!configApp.FirstDayIsSunday)
                        dtS = dtS.AddDays(1);

                    dtE = dtS.AddDays(6);
                    break;
                case 3:
                    listViewEntry.ClearObjects();
                    listViewEntry.SetObjects(entryField.FindAll(ef => { return ef.AlertDate < DateTime.Now; }));
                    return;
            }

            listViewEntry.ClearObjects();
            listViewEntry.SetObjects(entryField.FindAll(ef => { return ef.Date >= dtS && ef.Date <= dtE; }));
        }

        private void OnEntrysFilter(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if (dateTimePickerDetailStart.Value <= dateTimePickerDetailEnd.Value)
                sb.Append("Date >= '" + dateTimePickerDetailStart.Value.Date + " ' And Date <= '" +
                    dateTimePickerDetailEnd.Value.Date + " '");

            if (numericUpDownDetailEnd.Value != 0)
            {
                if (sb.Length > 0)
                    sb.Append(" And ");

                sb.Append("Money >= " + numericUpDownDetailStart.Value + " And Money <= " +
                    numericUpDownDetailEnd.Value + " ");
            }

            List<EntryField> fields = new List<EntryField>();
            foreach (DataRow row in KMData.DataTableEntrys.Select(sb.ToString()))
                fields.Add(new EntryField(row));

            if (checkBoxDetailIncome.Checked && !checkBoxDetailExpenses.Checked)
                fields = fields.FindAll(delegate(EntryField ef) { return ef.Money > 0; });
            else if (!checkBoxDetailIncome.Checked && checkBoxDetailExpenses.Checked)
                fields = fields.FindAll(delegate(EntryField ef) { return !(ef.Money < 0); });

            listViewEntry.ClearObjects();
            listViewEntry.SetObjects(fields);
        }

        private void OnLeftPanelExpanding(object sender, BSE.Windows.Forms.XPanderStateChangeEventArgs e)
        {
            if (configMainForm.UItype == UiType.Money)
            {
                listViewGtd1.Visible = false;
                treeViewExGroup.Visible = true;
            }
            else
            {
                listViewGtd1.Visible = true;
                treeViewExGroup.Visible = false;
            }
        }
        #endregion

    }
}